package com.sjgl.esdn.service.impl;

import com.sjgl.esdn.constant.FileConstantsESDN;
import com.sjgl.esdn.domain.entity.File;
import com.sjgl.esdn.domain.entity.uc.*;
import com.sjgl.esdn.mapper.*;
import com.sjgl.esdn.service.FileService;
import com.sjgl.esdn.service.UserCenterService;
import com.sjgl.esdn.utils.DateUtilsESDN;
import com.sjgl.esdn.utils.FileUtilsESDN;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @Author: cjb
 * @Date: 2022-09-01 09:35
 **/
@Service
public class UserCenterServiceImpl implements UserCenterService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCenterMapper userCenterMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private FileLikeMapper fileLikeMapper;

    @Autowired
    private ConfigSuffixMapper configSuffixMapper;

    @Autowired
    private FileBoxroomMapper fileBoxroomMapper;

    @Autowired
    private BoxroomMapper boxroomMapper;

    @Autowired
    private FileBrowseMapper fileBrowseMapper;

    @Autowired
    private FileDeptMapper fileDeptMapper;

    @Autowired
    private FileDownloadMapper fileDownloadMapper;

    @Autowired
    private UCMessageMapper ucMessageMapper;

    @Autowired
    private UCBlogMapper ucBlogMapper;

    @Autowired
    private MyColumnMapper myColumnMapper;

    @Override
    public String selectUserPasswordById(Long userId){
        return userMapper.selectUserPasswordById(userId);
    }

    @Override
    public UserInfo selectUserInfoById(Long userId) {
        return userCenterMapper.selectUserInfoById(userId);
    }

    @Override
    public List<MyMessage> getMyMessage(Long userId) {
        List<MyMessage> myMessages = new ArrayList<>();
        List<UCMessage> UCMessages = ucMessageMapper.selectMessageByUserId(userId) ;
        int count=0;
        for(UCMessage UCMessage:UCMessages){
            if(++count>50){
                break;
            }
//            if(UCMessage.getMessageType()==41||UCMessage.getMessageType()!=42||UCMessage.getMessageType()!=51||UCMessage.getMessageType()==61){
//                continue;
//            }
            Long userId2=UCMessage.getUserId1();
            String avatar = userId2.toString() + ".jpg";
            String prePath = "D:\\ESDN\\";
            String avatarPath = prePath + configSuffixMapper.selectFolderByContent("avatar") + avatar;
            java.io.File file1= new java.io.File(avatarPath);
            if (!file1.exists()) {
                avatarPath = prePath + configSuffixMapper.selectFolderByContent("avatar") + "0.jpg";
            }
            String avatarJPG = FileUtilsESDN.fileToBase64(avatarPath);
            String userName =  userMapper.getUserName(userId2);
            Date createTime=UCMessage.getCreateTime();
            Long type=UCMessage.getMessageType();
            if(type==10){//资源评论
                int flag=UCMessage.getIsBlog();
                Long targetId=UCMessage.getFileId();
                String targetName=fileService.selectFileById(targetId).getFileName();
                myMessages.add(new MyMessage(avatarJPG,userId2,userName,flag,"评论",targetId,targetName,createTime));
            }
//            else if(type==11){//回复评论
//                Long targetId=UCMessage.getCommentId();
//                String content=ucMessageMapper.selectContentByCommentId(targetId);
//                myMessages.add(new MyMessage(avatarJPG,userId2,userName,2,"回复",targetId,content,createTime));
//            }
            else if(type==20){//资源点赞
                int flag=UCMessage.getIsBlog();
                Long targetId=UCMessage.getFileId();
                String targetName=fileService.selectFileById(targetId).getFileName();
                myMessages.add(new MyMessage(avatarJPG,userId2,userName,flag,"点赞",targetId,targetName,createTime));
            }
//            else if(type==21){//评论点赞
//                Long targetId=UCMessage.getCommentId();
//                String content=ucMessageMapper.selectContentByCommentId(targetId);
//                myMessages.add(new MyMessage(avatarJPG,userId2,userName,2,"点赞",targetId,content,createTime));
//            }
            else if(type==31){//资源收藏
                int flag=UCMessage.getIsBlog();
                Long targetId=UCMessage.getFileId();
                String targetName=fileService.selectFileById(targetId).getFileName();
                myMessages.add(new MyMessage(avatarJPG,userId2,userName,flag,"收藏",targetId,targetName,createTime));
            }
            else if(type==51){//资源下载
                int flag=UCMessage.getIsBlog();
                Long targetId=UCMessage.getFileId();
                String targetName=fileService.selectFileById(targetId).getFileName();
                myMessages.add(new MyMessage(avatarJPG,userId2,userName,flag,"下载",targetId,targetName,createTime));
            }
        }

        myMessages.sort(new Comparator<MyMessage>() {
            @Override
            public int compare(MyMessage o1, MyMessage o2) {
                Date date1 = o1.getTime();
                Date date2 = o2.getTime();
                return date2.compareTo(date1);
            }
        });

        return myMessages;
    }

    @Override
    public List<RecentBrowse> getRecentBrowseFile(@Param("userId") Long userId) {

        List<RecentBrowse> recentBrowses = new ArrayList<>();

        Long[] fileIds = fileBrowseMapper.selectFilesByUserId(userId);
        System.out.println(fileIds.length);
        for (Long fileId : fileIds) {
            System.out.println(fileId);

            UCFile file = fileMapper.selectByFileId(fileId);
            String fileName = file.getFileName();
            String author = fileMapper.selectAuthorByFileId(fileId);
            Long authorId = fileMapper.selectAuthorIdByFileId(fileId);
            String avatar = authorId.toString() + ".jpg";
            String prePath = "D:\\ESDN\\";
            String avatarPath = prePath + configSuffixMapper.selectFolderByContent("avatar") + avatar;
            java.io.File file1= new java.io.File(avatarPath);
            if (!file1.getParentFile().exists()) {
                avatarPath = prePath + configSuffixMapper.selectFolderByContent("avatar") + "0.jpg";
            }
            String avatarJPG = FileUtilsESDN.fileToBase64(avatarPath);

            Date createTime = fileBrowseMapper.selectCreateTimeByKey(userId, fileId);
            String path = fileService.selectPreviewPath(fileId);
            String fileJPG = FileUtilsESDN.fileToBase64(path);

            RecentBrowse recentBrowse = new RecentBrowse(fileId, fileName, author,avatarJPG, createTime, fileJPG, file.getDownloadNum());
            recentBrowses.add(recentBrowse);
        }
        recentBrowses.sort(new Comparator<RecentBrowse>() {
            @Override
            public int compare(RecentBrowse o1, RecentBrowse o2) {

                Date date1 = o1.getCreateTime();
                Date date2 = o2.getCreateTime();
                return date2.compareTo(date1);
            }
        });
        // 限制大小
        if (recentBrowses.size() > 50) {
            List<RecentBrowse> newRecentBrowse = new ArrayList<>();
            for (int i = 0; i < 50; i++) {
                newRecentBrowse.add(recentBrowses.get(i));
            }
            return newRecentBrowse;
        } else {
            return recentBrowses;
        }
    }



    @Override
    public void updateUserInfo(UserInfo userInfo) {
        Long userId = userInfo.getUserId();
        userCenterMapper.updateUserName(userInfo.getUserName(),userId);
        userCenterMapper.updateNickName(userInfo.getNickName(),userId);
        userCenterMapper.updatePhonenumber(userInfo.getPhonenumber(),userId);
        userCenterMapper.updateSex(userInfo.getSex(),userId);
        userCenterMapper.updateEmail(userInfo.getEmail(),userId);
        userCenterMapper.updateBirthday(userInfo.getBirthday(),userId);
    }

    @Override
    public List<BrowseHistory> getBrowseHistory(Long userId) {
        List<BrowseHistory> browseHistoryList = new ArrayList<>();
        Long[] fileIds = fileBrowseMapper.selectFilesByUserId(userId);
        for (Long fileId : fileIds) {
            UCFile file = fileMapper.selectByFileId(fileId);
            String fileName = file.getFileName();
            String fileSuffix = file.getFileSuffix();
            Date createTime = fileBrowseMapper.selectCreateTimeByKey(userId, fileId);
            browseHistoryList.add(new BrowseHistory(fileId,fileName,fileSuffix,createTime));
        }
        browseHistoryList.sort(new Comparator<BrowseHistory>() {
            @Override
            public int compare(BrowseHistory o1, BrowseHistory o2) {
                Date date1 = o1.getCreateTime();
                Date date2 = o2.getCreateTime();
                return date2.compareTo(date1);
            }
        });
        return browseHistoryList;
    }

    @Override
    public List<UploadFile> getUploadFile(Long userId) {
        List<UploadFile> uploadFiles = new ArrayList<>();
        List<File> files = fileMapper.selectByCreateBy(userId);
        for(File file:files){
            String flag;
            List<String> depts;
            Long fileId = file.getFileId();
            String fileName = file.getFileName();
            Integer fileType = file.getFileType();
            String fileSuffix = file.getFileSuffix();
            String[] label = fileDeptMapper.selectLabelByFileId(fileId);
            String column = fileMapper.selectColumnByFileId(fileId);
            Date createTine = fileMapper.selectCreateTimeByFileId(fileId);
            if (fileType==0){
                flag = "仅我可见";
                depts = null;
            }
            else if(fileType==1){
                flag = "全部可见";
                depts = fileDeptMapper.selectAllDeptName();
            }
            else if(fileType==2){
                flag = "部分可见";
                depts = fileDeptMapper.selectDeptName(fileId);
            }
            else{
                flag = "谁不可见";
                depts = fileDeptMapper.selectDeptName(fileId);
            }
            uploadFiles.add(new UploadFile(fileId,fileName,fileSuffix,label,column,flag,createTine,depts));
        }
        return uploadFiles;
    }


    public void updateUploadFile(UploadFile uploadFile,List<Long> deptIds){
        String type = uploadFile.getFlag();
        Integer flag;
        if("全部可见".equals(type)){
            flag=1;
        }else if("部分可见".equals(type)){
            flag=2;
        }else if("谁不可见".equals(type)){
            flag=3;
        }
        else{
            flag=0;
        }
        fileMapper.updateUploadFile(uploadFile.getFileId(), flag);
        //文件、部门取消关联
        fileMapper.deleteFileDept(uploadFile.getFileId());
        //文件、部门重新关联
        if (type.equals("全部可见") ) {
            fileMapper.insertFileDept(uploadFile.getFileId(), -1L);
        } else if (type.equals("部分可见")||type.equals("谁不可见")) {
            for (Long deptId : deptIds) {
                fileMapper.insertFileDept(uploadFile.getFileId(), deptId);
            }
        }
    }


    @Override
    public List<MyDownloadFile> getMyDownLoadFile(Long userId) {
        List<MyDownloadFile> myDownLoadFiles = new ArrayList<>();
        Long[] fileIds = fileDownloadMapper.selectFileIdsByUserId(userId);

        for(Long fileId:fileIds){
            String fileName = fileMapper.selectFileNameByFileId(fileId);
            String fileSuffix = fileMapper.selectFileSuffixByFileId(fileId);
            String[] fileLabel = fileMapper.selectFileLabelByFileId(fileId);
            String column = fileMapper.selectColumnByFileId(fileId);
            String author = fileMapper.selectAuthorByFileId(fileId);
            Date downloadTime = fileMapper.selectDownloadTimeById(fileId,userId);
            myDownLoadFiles.add(new MyDownloadFile(fileId,fileName,fileSuffix,fileLabel,column,author,downloadTime));
        }
        return myDownLoadFiles;
    }

    @Override
    public List<UCBlog> getUCBlogs(Long userId){
        List<UCBlog> UCBlogs = new ArrayList<>();
        Long[] fileIds = fileMapper.selectFileIdByuserId(userId);
        for(Long fileId:fileIds){
            Integer isBlog = fileMapper.selectIsBlogByFileId(fileId);
            if(isBlog.equals(0)){
                continue;
            }
            String flag;
            Integer type = fileMapper.selectFileTypeByFileIdInteger(fileId);
            List<String> depts;
            if(type==0){
                flag="仅我可见";
                depts = null;
            }else if(type==1){
                flag="全部可见";
                depts = fileDeptMapper.selectAllDeptName();
            }else if(type==2){
                flag="部分可见";
                depts = fileDeptMapper.selectDeptName(fileId);
            }else{
                flag="谁不可见";
                depts = fileDeptMapper.selectDeptName(fileId);
            }
            String fileName = fileMapper.selectFileNameByFileId(fileId);
            String fileIntro= ucBlogMapper.selectFileIntroByFileId(fileId);
            Long browseNum = ucBlogMapper.selectBrowseNumByFileId(fileId);
            Long likeNum = ucBlogMapper.selectLikeNumByFileId(fileId);
            Long commentNum = ucBlogMapper.selectCommentNumByFileId(fileId);
            Long boxNum = ucBlogMapper.selectBoxNumByFileId(fileId);
            Date createTime = fileMapper.selectCreateTimeByFileId(fileId);
            UCBlogs.add(new UCBlog(fileId,fileName,fileIntro,flag,browseNum,likeNum,commentNum,boxNum,depts,createTime));
        }
        return UCBlogs;
    }
    @Override
    public void updateMyBlog(UCBlog ucBlog,List<Long> deptIdList){
        String type = ucBlog.getFlag();
        Integer flag;
        if("全部可见".equals(type)){
            flag=1;
        }else if("部分可见".equals(type)){
            flag=2;
        }else if("谁不可见".equals(type)){
            flag=3;
        }
        else{
            flag=0;
        }
        fileMapper.updateUploadFile(ucBlog.getFileId(), flag);
        //文件、部门取消关联
        fileMapper.deleteFileDept(ucBlog.getFileId());
        //文件、部门重新关联
        if (type.equals("全部可见")) {
            fileMapper.insertFileDept(ucBlog.getFileId(), -1L);
        } else if (type.equals("部分可见")||type.equals("谁不可见")) {
            for (Long deptId : deptIdList) {
                fileMapper.insertFileDept(ucBlog.getFileId(), deptId);
            }
        }
    }

    @Override
    public void createMyColumn(Long userId,String columnName,String columnIntro){
        myColumnMapper.createColumn(userId,columnName,columnIntro);
    }
    @Override
    public List<MyColumn> getMyColumn(Long userId){
        List<MyColumn> myColumns=new ArrayList<>();
        Long[] columnIds = myColumnMapper.selectColumnIdsByUserId(userId);
        for(Long columnId:columnIds){
            String columnName = myColumnMapper.selectColumnNameByColumnId(columnId);
            Date createTime = myColumnMapper.selectCreateTimeByColumnId(columnId);
            String img = columnId.toString() + ".jpg";
            String imgPath = "D:\\ESDN\\" + configSuffixMapper.selectFolderByContent("columnImage") + DateUtilsESDN.getYYYYMMByDate(createTime)+ "\\" + img;
            java.io.File file1= new java.io.File(imgPath);
            if (!file1.getParentFile().exists()) {
                imgPath = "D:\\ESDN\\" + configSuffixMapper.selectFolderByContent("columnImage") +"0.jpg";
            }
            String columnImg = FileUtilsESDN.fileToBase64(imgPath);
            Long articleNum = myColumnMapper.selectArticleNumByColumnId(columnId);
            myColumns.add(new MyColumn(columnId,columnName,columnImg,articleNum));
        }
        return myColumns;
    }

    @Override
    public MyColumnInfo getMyColumnInfo(Long columnId){
        String columnName = myColumnMapper.selectColumnNameByColumnId(columnId);
        Date createTime = myColumnMapper.selectCreateTimeByColumnId(columnId);
        String img = columnId.toString() + ".jpg";
        String imgPath = "D:\\ESDN\\" + configSuffixMapper.selectFolderByContent("columnImage") + DateUtilsESDN.getYYYYMMByDate(createTime)+ "\\" + img;
        java.io.File file1= new java.io.File(imgPath);
        if (!file1.getParentFile().exists()) {
            imgPath = "D:\\ESDN\\" + configSuffixMapper.selectFolderByContent("columnImage") +"0.jpg";
        }
        String columnImg = FileUtilsESDN.fileToBase64(imgPath);
        Long followNum = myColumnMapper.selectFollowNumByColumnId(columnId);
        Long articleNum = myColumnMapper.selectArticleNumByColumnId(columnId);
        Long browseNum = (long)0;
        Long likeNum = (long)0;
        Long commentNum = (long)0;
        Long boxNum = (long)0;
        String intro = myColumnMapper.selectColumnIntroByColumnId(columnId);
        Long[] fileIds = myColumnMapper.selectFileIdsByColumnId(columnId);
        List<UCBlog> UCBlogs = new ArrayList<>();
        for(Long fileId:fileIds){
            String fileName = fileMapper.selectFileNameByFileId(fileId);
            String fileIntro = fileMapper.selectFileIntroByFileId(fileId);
            Long browse = fileMapper.selectBrowseNumByFileId(fileId);
            Long like = fileMapper.selectLikeNumByFileId(fileId);
            Long comment = fileMapper.selectCommentNumByFileId(fileId);
            Long box = fileMapper.selectBoxNumByFileId(fileId);
            Date create = fileMapper.selectCreateTimeByFileId(fileId);
            browseNum += browse;
            likeNum += like;
            commentNum += comment;
            boxNum += box;
            UCBlogs.add(new UCBlog(fileId,fileName,fileIntro,null,browse,like,comment,box,null,create));
        }
        MyColumnInfo myColumnInfo=new MyColumnInfo(columnId,columnName,columnImg,followNum,articleNum,browseNum,boxNum,intro,UCBlogs);
        return  myColumnInfo;
    }

    @Override
    public String getAvatar() {
        return configSuffixMapper.selectFolderByContent("avatar");
    }

    @Override
    public String getColumnImg(Long columnId){
        return configSuffixMapper.selectFolderByContent("columnImage")+ DateUtilsESDN.getYYYYMMByDate(myColumnMapper.selectCreateTimeByColumnId(columnId));
    }

}
